<template>
    <section class="rent-currency-exchange-mall">
        <div class="section-header">
            <h2>兑换商城<van-icon class="question-icon" color="#999999" name="question-o" /></h2>
            <div class="exchange-record ">兑换记录<van-icon size="14" color="#D7D7D7" name="arrow" /></div>
        </div>
        <!-- 条件筛选标签 -->
        <div class="filter-tabs">
            <div class="filter-tab" v-for="tab in filterTabs" :key="tab.id" :class="{ active: activeTab === tab.id }"
                @click="handleTabClick(tab.id)">
                <div style="height: 5px;"></div>
                <span>{{ tab.label }}</span>
                <div style="height: 5px;"></div>
            </div>
        </div>   



        <div class="product" ref="scrollContainer" @scroll="handleScroll">
            <div v-if="!isLoading && productList.length === 0" class="empty-state">
                <p>暂无符合条件的商品</p>
            </div>
            <div class="product-grid">
                <product-card v-for="product in productList" :key="product.id" :product="product" />
                <van-loading class="loading-center" type="spinner" size="15" v-show="isLoading" text="加载中..." />
            </div>
        </div>
        <!-- <button v-if="!hasMore" class="load-more-btn">赚取更多租币 &gt;</button> -->
        <div class="load-more-container">
            <button class="load-more-btn" @click="handleClick">赚取更多租币<van-icon name="arrow" /></button>
        </div>
    </section>
</template>

<script setup lang="ts">
import ProductCard from './ProductCard.vue'
import { ref, onMounted } from 'vue';
import router from '@/router'
const handleClick = () => {
    router.push('/task');
};
// 定义商品类型
import type { Product } from '../data';
// 筛选标签数据
// 导入筛选标签数据
import { filterTabs } from '../config';

const activeTab = ref('all');

// 导入图片
import productImage from '@/assets/shopStoreImg/Bitmap@2x(3).png';
// --- 模拟后端数据和API ---
const allProducts: Product[] = Array.from({ length: 100 }, (_, i) => ({
    id: i + 1,
    title: `顶配 iPhone 16,商品 ${i + 1} 号`,
    currencyPrice: 50 + Math.floor(Math.random() * 6000),
    cashPrice: parseFloat((Math.random() * 20).toFixed(1)),
    originalPrice: parseFloat((10 + Math.random() * 30).toFixed(1)),
    sales: Math.floor(Math.random() * 3000),
    isFreeShipping: Math.random() > 0.5,
    imageUrl: productImage
}));

const PAGE_SIZE = 10;
// 模拟API请求
const fetchProductsAPI = async (page: number, filter: string): Promise<{ data: Product[], hasMore: boolean }> => {
    console.log(`Fetching page: ${page}, filter: ${filter}`);
    // 1. 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));

    // 2. 根据 filter 筛选数据
    let filtered = allProducts;
    if (filter !== 'all') {
        const [min, max] = filter.split('-').map(Number);
        filtered = allProducts.filter(p => {
            if (filter.includes('+')) return p.currencyPrice >= 5000;
            if (min === undefined || max === undefined) return { data: [], hasMore: false };
            return p.currencyPrice >= min && p.currencyPrice <= max;
        });
    }

    // 3. 根据 page 进行分页
    const start = (page - 1) * PAGE_SIZE;
    const end = start + PAGE_SIZE;
    const paginatedData = filtered.slice(start, end);
    console.log(end, filtered.length, end < filtered.length);
    // 4. 返回数据和是否还有更多
    return {
        data: paginatedData,
        hasMore: end < filtered.length,
    };
};
// 模拟商品列表数据
const productList = ref<Product[]>([]);
// 分页和加载状态
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);
// 获取滚动容器的DOM引用
const scrollContainer = ref<HTMLElement | null>(null);

// 核心函数：获取商品数据
const fetchProducts = async () => {
    // 防止重复加载
    if (isLoading.value || !hasMore.value) return;

    isLoading.value = true;
    try {
        const { data, hasMore: moreData } = await fetchProductsAPI(currentPage.value, activeTab.value);
        console.log('获取到的商品数据:', data, hasMore.value);
        if (currentPage.value === 1) {
            // 如果是第一页，直接替换列表
            productList.value = data;
        } else {
            // 否则，追加到列表末尾
            productList.value.push(...data);
        }
        hasMore.value = moreData;
    } catch (error) {
        console.error('获取商品失败', error);
    } finally {
        isLoading.value = false;
    }
};

// 点击筛选标签的处理器
const handleTabClick = (tabId: string) => {
    // 如果点击的是当前已激活的tab，则不执行任何操作
    if (activeTab.value === tabId) return;

    activeTab.value = tabId;
    // 重置状态
    productList.value = []; // 立即清空，提供更好的用户反馈
    currentPage.value = 1;
    hasMore.value = true;
    // 重新加载数据
    fetchProducts();
};

// 滚动事件处理器
const handleScroll = () => {
    // 如果正在加载或没有更多数据了，则不处理
    if (isLoading.value || !hasMore.value) return;

    const container = scrollContainer.value;
    if (container) {
        const { scrollTop, clientHeight, scrollHeight } = container;
        console.log('scrollTop:', scrollTop, 'clientHeight:', clientHeight, 'scrollHeight:', scrollHeight);
        // 判断是否滚动到底部（预留50px的触发阈值）
        if (scrollTop + clientHeight >= scrollHeight - 50) {
            currentPage.value++;
            fetchProducts();
        }
    }
};

// 组件挂载时，加载第一页数据
onMounted(() => {
    fetchProducts();
});
</script>

<style scoped lang="scss">
// 定义通用变量
$primary-orange: #ff6a00;
$light-gray-bg: #f7f8fa;

.rent-currency-exchange-mall {
    display: flex;
    flex-direction: column;
    height: 60.8vh;
    background-color: #ffffff;
    border-radius: 30px 30px 0px 0px;
    padding: 0 21px;

    .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 23px 0;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 17px;
        color: #222222;
        font-style: normal;

        h2 {
            font-weight: 600;

            .question-icon {
                margin-left: 4px;
            }
        }

        .exchange-record {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 15px;
            color: #999999;
            line-height: 15px;
            text-align: left;
            font-style: normal;
        }
    }

    .filter-tabs {
        display: flex;
        justify-content: space-between;
        margin-bottom: 17px;

        .filter-tab {
            background-color: #fff;
            border: 1px solid #E6E6E6;
            color: #999999;
            padding: 0 9px;
            border-radius: 16px;
            font-size: 13px;
            &.active {
                color: $primary-orange;
                background: rgba(255, 106, 0, 0.1);
                font-weight: 500;
                border: none;
            }
        }
    }

    .product {
        overflow-y: auto;
        padding-right: 5px;

        .empty-state {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 15px;
        }

        .product-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            padding-bottom: 10px;

            .loading-center {
                grid-column: 1 / -1; // 跨两列显示
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100px; // 设置高度以确保垂直居中
            }

        }
    }

    .load-more-container {
        z-index: 1000;
        position: fixed;
        bottom: 0px;
        left: 50%;
        transform: translateX(-50%);
        height: 50px;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;

        .load-more-btn {
            width: 133px;
            padding: 7px 0;
            background-color: #fff;
            border: 1px solid #FF6737;
            border-radius: 20px;
            color: #FF6737;
            font-size: 15px;
            text-align: center;
        }
    }


}
</style>